package ICM.client;

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Observable;
import java.util.Observer;
import java.util.Vector;

import javax.annotation.processing.Messager;
import javax.swing.*;
import javax.swing.border.*;

import common.*;

import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;

public class CommitteeUI extends JPanel implements ActionListener,Observer {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private ClientUI ui;
	private Client c;
	private User[] committee = null;
	private SystemEngineer[] syseng = null;
	private JTable table;
	private JTable table2;
	private DefaultTableModel defaultModel = null;
	private DefaultTableModel defaultModel2 = null;
	private Vector newRow = null;
	private boolean ChangeCommitteeMember = false;
	private boolean NewCommitteeMember = false;
	private JLabel lblId;
	private JLabel lblFirstName;
	private JLabel lblLastName;
	private JLabel lblRole;
	private JLabel lblEmail;
	private JLabel lblDepartment;
	private JTextPane UserID;
	private JTextPane FirstName;
	private JTextPane LastName;
	private JTextPane Role;
	private JTextPane Email;
	private JTextPane Department;
	private JButton btnAddNewMember;
	private JButton btnChangeThisMember;
	private JLabel lblChooseAnEmployee;
	private JComboBox EmployeesBox;
	private JButton btnSaveChanges;
	private JButton btnBack;
	private JLabel lblChooseAnEmployee_1;
	private JComboBox EmployeesBox2;
	private JButton btnSaveChanges_1;
	private JComboBox RoleBox;
	private JLabel lblChooseARole;
	
	public CommitteeUI(final Client c, final ClientUI ui) {
		this.c = c;
		this.ui = ui;
		c.addObserver(this);
		setLayout(null);
		int i;
		
		JLabel lblCommitteeMembers = new JLabel("Change committee");
		lblCommitteeMembers.setFont(new Font("Tahoma", Font.PLAIN, 26));
		lblCommitteeMembers.setBounds(425, 11, 250, 60);
		add(lblCommitteeMembers);
		
		CommandMessage msg1 = new CommandMessage("Get committee members",null);
		// requests.
		try {
			c.sendToServer(msg1);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
		    Thread.sleep(200);
		} catch(InterruptedException ex) {
		    Thread.currentThread().interrupt();
		}
		
		CommandMessage msg11 = new CommandMessage("Get system engineers",null);
		// requests.
		try {
			c.sendToServer(msg11);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
		    Thread.sleep(200);
		} catch(InterruptedException ex) {
		    Thread.currentThread().interrupt();
		}
		
		table = new JTable();
		table.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				JTable target = (JTable)e.getSource();
				int row = target.getSelectedRow();
				
				if (!lblId.isVisible())
				{
					lblId.setVisible(true);
					lblFirstName.setVisible(true);
					lblLastName.setVisible(true);
					lblRole.setVisible(true);
					lblEmail.setVisible(true);
					lblDepartment.setVisible(true);
					UserID.setVisible(true);
					FirstName.setVisible(true);
					LastName.setVisible(true);
					Role.setVisible(true);
					Email.setVisible(true);
					Department.setVisible(true);
					btnChangeThisMember.setVisible(true);
				}
				
				lblChooseAnEmployee.setVisible(false);
				EmployeesBox.setVisible(false);
				btnSaveChanges.setVisible(false);
				
				UserID.setText(table.getValueAt(row, 0).toString());
				FirstName.setText(table.getValueAt(row, 1).toString());
				LastName.setText(table.getValueAt(row, 2).toString());
				Role.setText(table.getValueAt(row, 3).toString());
				Email.setText(table.getValueAt(row, 4).toString());
				Email.setToolTipText(Email.getText());
				Department.setText(table.getValueAt(row, 5).toString());
			}
		});
		table.setModel(new DefaultTableModel(
			new Object[][] {
			},
			new String[] {
				"ID", "First name", "Last name", "Role", "Email", "Department"
			}
		));
		defaultModel = (DefaultTableModel) table.getModel();
        if (committee!=null)
		{
			for (i=0;i<committee.length;i++)
			{
				newRow = new Vector();
				newRow.add(committee[i].getId());
		        newRow.add(committee[i].getFirstname());
		        newRow.add(committee[i].getLastname());
		        newRow.add(committee[i].getRole());
		        newRow.add(committee[i].getEmail());
		        newRow.add(committee[i].getDepartment());
		        defaultModel.addRow(newRow); 
			}
		}
		JScrollPane pane = new JScrollPane(table); 
		pane.setBounds(45, 90, 496, 110);
		add(pane);
		
		lblId = new JLabel("ID:");
		lblId.setVisible(false);
		lblId.setBounds(70, 235, 46, 14);
		add(lblId);
		
		lblFirstName = new JLabel("First name:");
		lblFirstName.setVisible(false);
		lblFirstName.setBounds(70, 260, 64, 14);
		add(lblFirstName);
		
		lblLastName = new JLabel("Last name:");
		lblLastName.setVisible(false);
		lblLastName.setBounds(70, 285, 64, 14);
		add(lblLastName);
		
		lblRole = new JLabel("Role:");
		lblRole.setVisible(false);
		lblRole.setBounds(70, 310, 46, 14);
		add(lblRole);
		
		lblEmail = new JLabel("Email:");
		lblEmail.setVisible(false);
		lblEmail.setBounds(70, 335, 46, 14);
		add(lblEmail);
		
		lblDepartment = new JLabel("Department:");
		lblDepartment.setVisible(false);
		lblDepartment.setBounds(70, 359, 64, 14);
		add(lblDepartment);
		
		UserID = new JTextPane();
		UserID.setEditable(false);
		UserID.setVisible(false);
		UserID.setBounds(140, 229, 135, 20);
		add(UserID);
		
		FirstName = new JTextPane();
		FirstName.setEditable(false);
		FirstName.setVisible(false);
		FirstName.setBounds(140, 254, 135, 20);
		add(FirstName);
		
		LastName = new JTextPane();
		LastName.setEditable(false);
		LastName.setVisible(false);
		LastName.setBounds(140, 279, 135, 20);
		add(LastName);
		
		Role = new JTextPane();
		Role.setEditable(false);
		Role.setVisible(false);
		Role.setBounds(140, 304, 135, 20);
		add(Role);
		
		Email = new JTextPane();
		Email.setEditable(false);
		Email.setVisible(false);
		Email.setBounds(140, 329, 135, 20);
		add(Email);
		
		Department = new JTextPane();
		Department.setEditable(false);
		Department.setVisible(false);
		Department.setBounds(140, 353, 135, 20);
		add(Department);
		
		btnAddNewMember = new JButton("Add new member",new ImageIcon(CommitteeUI.class.getResource("/client/images/add.png")));
		btnAddNewMember.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				lblChooseAnEmployee_1.setVisible(true);
				EmployeesBox2.setVisible(true);
				btnSaveChanges_1.setVisible(true);
				lblChooseARole.setVisible(true);
				RoleBox.setVisible(true);
				lblChooseAnEmployee.setVisible(false);
				EmployeesBox.setVisible(false);
				btnSaveChanges.setVisible(false);
			}
		});
		btnAddNewMember.setBounds(425, 444, 181, 33);
		add(btnAddNewMember);
		
		btnChangeThisMember = new JButton("Change this member");
		btnChangeThisMember.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				lblChooseAnEmployee.setVisible(true);
				EmployeesBox.setVisible(true);
				btnSaveChanges.setVisible(true);
				lblChooseAnEmployee_1.setVisible(false);
				EmployeesBox2.setVisible(false);
				btnSaveChanges_1.setVisible(false);
				lblChooseARole.setVisible(false);
				RoleBox.setVisible(false);
			}
		});
		btnChangeThisMember.setVisible(false);
		btnChangeThisMember.setBounds(310, 281, 153, 23);
		add(btnChangeThisMember);
		
		lblChooseAnEmployee = new JLabel("Choose a system engineer:");
		lblChooseAnEmployee.setVisible(false);
		lblChooseAnEmployee.setBounds(487, 235, 181, 14);
		add(lblChooseAnEmployee);
		
		EmployeesBox = new JComboBox();
		EmployeesBox.setVisible(false);
		EmployeesBox.setBounds(497, 281, 153, 22);
		add(EmployeesBox);
		
		btnSaveChanges = new JButton("Save changes" , new ImageIcon(CommitteeUI.class.getResource("/client/images/save.png")));
		btnSaveChanges.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int i;
				String newCommitteeMember = EmployeesBox.getSelectedItem().toString();
				// Supervisor change request
				CommandMessage msg = new CommandMessage("Change committee member",new String[] {UserID.getText(),newCommitteeMember});
				try {
					c.sendToServer(msg);
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				try {
				    Thread.sleep(200);
				} catch(InterruptedException ex) {
				    Thread.currentThread().interrupt();
				}
				if (ChangeCommitteeMember)
				{
					int row = table.getSelectedRow();
					String role = table.getValueAt(table.getSelectedRow(), 3).toString();
					table.setValueAt(EmployeesBox.getSelectedItem(), row, 0);
					table.setValueAt(syseng[EmployeesBox.getSelectedIndex()].getFirstname(), row, 1);
					table.setValueAt(syseng[EmployeesBox.getSelectedIndex()].getLastname(), row, 2);
					table.setValueAt(role, row, 3);
					table.setValueAt(syseng[EmployeesBox.getSelectedIndex()].getEmail(), row, 4);
					table.setValueAt(syseng[EmployeesBox.getSelectedIndex()].getDepartment(), row, 5);
					CommandMessage msg11 = new CommandMessage("Get system engineers",null);
					// requests.
					try {
						c.sendToServer(msg11);
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					try {
					    Thread.sleep(200);
					} catch(InterruptedException ex) {
					    Thread.currentThread().interrupt();
					}
					if (syseng!=null)
					{
						EmployeesBox.removeAllItems();
						EmployeesBox2.removeAllItems();
						for (i=0;i<syseng.length;i++)
						{
							EmployeesBox.addItem(syseng[i].getId());
							EmployeesBox2.addItem(syseng[i].getId());
						}
					}
					ui.ShowMessageBox("Information", "Committee member was changed" ,JOptionPane.INFORMATION_MESSAGE);
				}
				else
					ui.ShowMessageBox("Error", "Can't change committee member" ,JOptionPane.ERROR_MESSAGE);
			}
		});
		btnSaveChanges.setVisible(false);
		btnSaveChanges.setBounds(518, 326, 114, 23);
		add(btnSaveChanges);
		
		btnBack = new JButton("Back" ,new ImageIcon(CommitteeUI.class.getResource("/client/images/back.png")));
		btnBack.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					ui.SetContent(ClientUI.Main_Screen);
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} 
			}
		});
		btnBack.setBounds(247, 444, 121, 33);
		add(btnBack);
		
		lblChooseAnEmployee_1 = new JLabel("Choose a system engineer:");
		lblChooseAnEmployee_1.setVisible(false);
		lblChooseAnEmployee_1.setBounds(636, 414, 164, 14);
		add(lblChooseAnEmployee_1);
		
		EmployeesBox2 = new JComboBox();
		EmployeesBox2.setVisible(false);
		EmployeesBox2.setBounds(646, 439, 142, 22);
		add(EmployeesBox2);
		
		btnSaveChanges_1 = new JButton("Save changes");
		btnSaveChanges_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int i;
				int countHeadOfCommittee=0;
				int countCommitteeMembers=0;
				for (i=0; i<committee.length; i++)
				{
					if (committee[i].getRole().equals("Head of committee"))
						countHeadOfCommittee++;
					else
						countCommitteeMembers++;
				}
				if (table.getRowCount()>=3 || (countCommitteeMembers>=2 && RoleBox.getSelectedItem().toString()=="Committee member") || (countHeadOfCommittee>=1 && RoleBox.getSelectedItem().toString()=="Head of committee"))
					ui.ShowMessageBox("Error", "Can't add a new committee member" ,JOptionPane.ERROR_MESSAGE);
				else
				{
					String newCommitteeMember = EmployeesBox2.getSelectedItem().toString();
					// Supervisor change request
					CommandMessage msg = new CommandMessage("New committee member",new String[] {newCommitteeMember,RoleBox.getSelectedItem().toString()});
					try {
						c.sendToServer(msg);
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					try {
					    Thread.sleep(200);
					} catch(InterruptedException ex) {
					    Thread.currentThread().interrupt();
					}
					if (NewCommitteeMember)
					{
						CommandMessage msg1 = new CommandMessage("Get committee members",null);
						// requests.
						try {
							c.sendToServer(msg1);
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
						try {
						    Thread.sleep(200);
						} catch(InterruptedException ex) {
						    Thread.currentThread().interrupt();
						}
						int row = table.getSelectedRow();
						for (i=0; i<committee.length; i++)
							if (committee[i].getId()==Integer.parseInt(newCommitteeMember))
								break;
						newRow = new Vector();
						newRow.add(committee[i].getId());
				        newRow.add(committee[i].getFirstname());
				        newRow.add(committee[i].getLastname());
				        newRow.add(committee[i].getRole());
				        newRow.add(committee[i].getEmail());
				        newRow.add(committee[i].getDepartment());
				        defaultModel.addRow(newRow);
						if (syseng!=null)
						{
							EmployeesBox.removeAllItems();
							EmployeesBox2.removeAllItems();
							for (i=0;i<syseng.length;i++)
							{
								EmployeesBox.addItem(syseng[i].getId());
								EmployeesBox2.addItem(syseng[i].getId());
							}
						}
						CommandMessage msg11 = new CommandMessage("Get system engineers",null);
						// requests.
						try {
							c.sendToServer(msg11);
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
						try {
						    Thread.sleep(200);
						} catch(InterruptedException ex) {
						    Thread.currentThread().interrupt();
						}
						ui.ShowMessageBox("Information", "Committee member was added" ,JOptionPane.INFORMATION_MESSAGE);
					}
					else
						ui.ShowMessageBox("Error", "Can't add a new committee member" ,JOptionPane.ERROR_MESSAGE);
				}
			}
		});
		btnSaveChanges_1.setVisible(false);
		btnSaveChanges_1.setBounds(657, 559, 121, 23);
		add(btnSaveChanges_1);
		
		RoleBox = new JComboBox();
		RoleBox.setVisible(false);
		RoleBox.setBounds(645, 513, 143, 20);
		
		RoleBox.addItem("Committee member");
		RoleBox.addItem("Head of committee");
		
		add(RoleBox);
		
		lblChooseARole = new JLabel("Choose a role:");
		lblChooseARole.setVisible(false);
		lblChooseARole.setBounds(637, 488, 100, 14);
		
		add(lblChooseARole);
		
		table2 = new JTable();
		table2.setEnabled(false);
		table2.setModel(new DefaultTableModel(
			new Object[][] {
			},
			new String[] {
				"ID", "First name", "Last name", "Role", "Email", "Department"
			}
		));
		defaultModel2 = (DefaultTableModel) table2.getModel();
        if (syseng!=null)
		{
			for (i=0;i<syseng.length;i++)
			{
				newRow = new Vector();
				newRow.add(syseng[i].getId());
		        newRow.add(syseng[i].getFirstname());
		        newRow.add(syseng[i].getLastname());
		        newRow.add(syseng[i].getRole());
		        newRow.add(syseng[i].getEmail());
		        newRow.add(syseng[i].getDepartment());
		        defaultModel2.addRow(newRow); 
			}
		}
        TableColumnModel colModel = table2.getColumnModel();
        for(int j = 0; j < colModel.getColumnCount(); j++)
        	colModel.getColumn(j).setCellRenderer(new RowRenderer());
        
		JScrollPane scrollPane = new JScrollPane(table2);
		scrollPane.setBounds(561, 90, 502, 110);
		add(scrollPane);
		
		JLabel lblCommitteeMembers_1 = new JLabel("Committee members:");
		lblCommitteeMembers_1.setBounds(45, 65, 153, 14);
		add(lblCommitteeMembers_1);
		
		JLabel lblSystemEngineers = new JLabel("System engineers:");
		lblSystemEngineers.setBounds(561, 65, 114, 14);
		add(lblSystemEngineers);
		
		if (syseng!=null)
			for (i=0;i<syseng.length;i++)
			{
				EmployeesBox.addItem(syseng[i].getId());
				EmployeesBox2.addItem(syseng[i].getId());
			}
	}
	
	/**
	 * Handle massage from Observable class in our case Client
	 */
	@Override
	public void update(Observable arg0, Object arg1) {
		String msg = "";
		String cmd = "";
		if (arg1 instanceof TextMessage)
			msg = ((TextMessage)arg1).ToDebugMessage();
		else if (arg1 instanceof CommandMessage) {
			CommandMessage ms=(CommandMessage)arg1;
			if(ms.getCommand().equals("Committee members"))
				committee = (User[]) ms.getParams()[1];
			else if(ms.getCommand().equals("All system engineers"))
				syseng = (SystemEngineer[]) ms.getParams()[1];
			else if(ms.getCommand().equals("Committee member changed"))
				ChangeCommitteeMember = Boolean.parseBoolean(ms.getParams()[1].toString());
			else if(ms.getCommand().equals("Committee member added"))
				NewCommitteeMember = Boolean.parseBoolean(ms.getParams()[1].toString());
		}
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		// TODO Auto-generated method stub
		
	}
}


class RowRenderer extends DefaultTableCellRenderer {
    public Component getTableCellRendererComponent(JTable table,
                                                   Object value,
                                                   boolean isSelected,
                                                   boolean hasFocus,
                                                   int row, int column) {
        super.getTableCellRendererComponent(table, value, isSelected,
                                            hasFocus, row, column);
        setToolTipText((String)table.getValueAt(row, 4));
        return this;
    }
}